<template>
  <el-form ref="form" :model="taskForm" :rules="rules">
    <el-form-item label="提示时间" prop="remindTime">
      <el-switch v-model="taskForm.remindOn"/>
      <el-date-picker
        v-show="taskForm.remindOn"
        v-model="taskForm.remindTime"
        type="datetime"
        placeholder="选择日期时间"
        align="right"
        format="yyyy-MM-dd HH:mm"
        :picker-options="pickerOptions"
      />
    </el-form-item>
    <el-form-item label="内容" prop="content">
      <el-input
        v-model="taskForm.content"
        type="textarea"
        :rows="3"
        max="500"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">
        确 定
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import * as dayjs from 'dayjs';
import taskApiBinder from '@/axios/task';

const remindDelay = 3;
const generateDefaultRemindTime = function () {
  return dayjs().add(remindDelay, 'minute').toDate();
};

export default {
  name: 'TaskFormComp',
  props: {
    taskId: {
      validator(value) {
        return typeof value === 'number' || value === '';
      },
      default: ''
    },
    customFormData: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    const _this = this;
    const validateRemindTime = function (rule, date, callback) {
      date = dayjs(date);
      const now = dayjs(new Date());
      if (!_this.taskForm.remindOn) {
        callback();
        return;
      }
      if (now.add(remindDelay, 'minute').isSameOrBefore(date, 'minute')) {
        callback();
      } else {
        callback(new Error(`提醒时间至少在当前的${remindDelay}分钟后`));
      }
    };
    return {
      taskForm: {
        content: '',
        remindOn: false,
        remindTime: generateDefaultRemindTime()
      },
      rules: {
        content: [
          { required: true, message: '输入任务内容', trigger: 'blur' }
        ],
        remindTime: [
          { validator: validateRemindTime, trigger: 'blur' }
        ]
      },
      pickerOptions: {
        disabledDate(date) {
          return date.getTime() < Date.now();
        }
      }
    };
  },
  async fetch() {
    if (this.taskId) {
      await this.getById();
    } else {
      this.resetForm();
    }
  },
  watch: {
    taskId(newId, oldId) {
      if (newId === oldId) {
        return;
      }
      if (newId) {
        this.getById();
        return;
      }
      this.resetForm();
    },
    customFormData(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.resetForm();
      }
    },
    'taskForm.remindOn'() {
      this.$refs.form.validateField('remindTime');
    }
  },
  created() {
    this.apis = taskApiBinder(this);
  },
  fetchOnServer: false,
  methods: {
    resetForm() {
      this.taskForm = Object.assign({
        content: '',
        remindOn: false,
        remindTime: generateDefaultRemindTime()
      }, this.customFormData);
    },
    async submitForm() {
      try {
        await this.$refs.form.validate();
      } catch (e) {
        return;
      }

      let emitInfo;
      const res = await this[this.taskId ? 'updateById' : 'createTask']();
      if (res.success) {
        if (this.taskId) {
          emitInfo = {
            type: 'updated',
            id: this.taskId
          };
        } else {
          emitInfo = {
            type: 'created',
            id: res.data.id
          };
          this.resetForm();
        }
        this.$emit('submitted', emitInfo);
      }
    },
    async getById() {
      const res = await this.apis.getById(this.taskId);
      const { content, remindTime } = res.data;
      this.taskForm = {
        content,
        remindOn: !!remindTime,
        remindTime: remindTime ? new Date(remindTime) : generateDefaultRemindTime()
      };
    },
    createTask() {
      const data = this.handleReqData(this.taskForm);
      return this.apis.create(data);
    },
    updateById() {
      const data = this.handleReqData(this.taskForm);
      return this.apis.updateById(this.taskId, data);
    },
    handleReqData({ content, remindOn, remindTime }) {
      const reqData = {};
      reqData.content = content;
      reqData.remindTime = remindOn ? dayjs(remindTime).format('YYYY-MM-DD HH:mm:ss') : null;
      return reqData;
    }
  }
};
</script>

<style scoped lang="scss">

</style>
